var listColumns = [[
    {field: "id", checkbox: true},
    {field: "workOrderId", title: "工单号", align: "center", width: 100},
    {field: "createMobile", title: "来电号码", align: "center", width: 100,hidden:true},
    {field: "creatorName", title: "报修人", align: "center", width: 100},
    {field: "callerDeptName", title: "部门", align: "center", width: 120},
    {field: "address", title: "地点", align: "center", width: 120},
    {field: "floor", title: "楼层", align: "center", width: 120  ,hidden:true},
    {field: "expectTime", title: "维修时间", align: "center", width: 120},
    {field: "machineType", title: "选项", align: "center", width: 100},
    {field: "repaireSubject", title: "判定常用", align: "center", width: 150},
    {field: "status", title: "当前状态", align: "center", width: 80,formatter:function (value) {
        switch(value){
            // 00:座席处理 01:调配 02:已接单 03:服务中 04:结束服务
            case "00": return "待流转";
            case "01": return "待调配";
            case "02": return "已接单";
            case "03": return "服务中";
            case "04": return "服务完成待评价";
            case "05": return "已评价";
            case "06": return "待接单";
            default: return "";
        }
    }},
    {field: "currentName", title: "负责工程师", align: "center", width: 150},
    {field: "createTime", title: "创建时间", align: "center", width: 100,formatter:function (value) {
        return formatDate(value);
    }},
    {field: "beginProcessTime", title: "开始时间", align: "center", width: 100,formatter:function (value) {
        return formatDate(value);
    }},
    {field: "endProcessTime", title: "结束时间", align: "center", width: 100,formatter:function (value) {
        return formatDate(value);
    }},
    {field: "picAddress", title: "图片路径", align: "center", hidden:'true',formatter:function (value) {
        return formatDate(value);
    }},
    {field: "description", title: "备注", align: "center", width: 150},
    {
        field: "handle", title: "处理", align: "center", width: 150, formatter: function (value, rowData,index) {
        var flag = rowData.status;
        var roleId = $("#session_roleId").val();
        if(roleId != 2 && roleId != 4){
            return "";
        }
       /* if (flag=='00' ) {
            return '<a class="layui-btn layui-btn-xs" onclick="handleCirculation('+rowData.id+','+index+')" style="text-decoration: none">流转</a>'
            + '<a class="layui-btn layui-btn-xs" onclick="handleRecord('+rowData.id+','+flag+')" style="text-decoration: none">派单</a>';
        }*/
        if (flag=='01' || flag=='02' || flag=='03' || flag == '06') {
            return '<a class="layui-btn layui-btn-xs" onclick="handleRecord('+rowData.id+','+flag+')" style="text-decoration: none">派单</a>'
            +'<a class="layui-btn layui-btn-xs" onclick="editData('+rowData.id+','+index+')" style="text-decoration: none">编辑</a>' +
                '<a class="layui-btn layui-btn-xs" onclick="endServer('+rowData.id+','+index+')" style="text-decoration: none">完成</a>'
        }
    }
    }
]];
function formatDate(value) {
    if(value == null || value == ''){
        return "";
    }
    return value.substr(5,value.length);
}
layui.config({
    base: "../static/agent-ui/js/"
});

$.fn.toJSON = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        var name = this.name;
        var value = this.value;
        var paths = this.name.split(".");
        var len = paths.length;
        var obj = o;
        $.each(paths, function (i, e) {
            if (i == len - 1) {
                if (obj[e]) {
                    if (!obj[e].push) {
                        obj[e] = [obj[e]];
                    }
                    obj[e].push(value || '');
                } else {
                    obj[e] = value || '';
                }
            } else {
                if (!obj[e]) {
                    obj[e] = {};
                }
            }
            obj = o[e];
        });
    });
    return o;
};
String.prototype.endWith=function(str){
    if(str==null||str==""||this.length==0||str.length>this.length)
        return false;
    if(this.substring(this.length-str.length)==str)
        return true;
    else
        return false;
    return true;
}

String.prototype.startWith=function(str){
    if(str==null||str==""||this.length==0||str.length>this.length)
        return false;
    if(this.substr(0,str.length)==str)
        return true;
    else
        return false;
    return true;
}
layui.use(["laypage", "layer", "validator", "tools", "form", "select", "laydate","autocomplete"], function () {
    var form = layui.form;
    var date = layui.laydate;
    var autocomplete = layui.autocomplete;
    date.render({
        elem: '#ringTime',
        type: 'datetime',
        range: true
    });


    var layer=layui.layer;

    $(function () {
        $('#list').datagrid({
            columns: listColumns,
            fitColumns: false,
            fit: true,
            singleSelect: true,
            pagination: true,
            pageSize: 30,
            pageList: [30, 50, 100, 1000],
            toolbar: '#receivedListHeader',
            method: 'get',
            url: ctx +'/repaireInfo/list',
            onLoadSuccess:function(data) {
                for(var i=0;i<data.rows.length;i++){
                    var value=data.rows[i].status;
                    switch(value){
                        // 01:调配 02:已接单 03:服务中 04:结束服务
                        case "01":
                            $(".datagrid-view2").find(".datagrid-body").find(".datagrid-row").eq(i).addClass("datagrid-row-01");
                            break;
                        case "02":
                            $(".datagrid-view2").find(".datagrid-body").find(".datagrid-row").eq(i).addClass("datagrid-row-02");
                            break;
                        case "03":
                            $(".datagrid-view2").find(".datagrid-body").find(".datagrid-row").eq(i).addClass("datagrid-row-03");
                            break;
                        case "04":
                            $(".datagrid-view2").find(".datagrid-body").find(".datagrid-row").eq(i).addClass("datagrid-row-04");
                            break;
                        case "05":
                            $(".datagrid-view2").find(".datagrid-body").find(".datagrid-row").eq(i).addClass("datagrid-row-05");
                            break;
                        case "06":
                            $(".datagrid-view2").find(".datagrid-body").find(".datagrid-row").eq(i).addClass("datagrid-row-06");
                            break;
                        default:
                            $(".datagrid-view2").find(".datagrid-body").find(".datagrid-row").eq(i).addClass("datagrid-row-00");
                    }
                }
            }
        });
    });

    $('#search_submit').on('click', function () {
        $('#list').datagrid('load', $('#search_form').toJSON());
    });

    $("#exportData").on("click",function () {
        $('#search_form').attr("action",ctx + '/repaireInfo/export');
        $('#search_form').submit();
    });
    $("#addData").on("click", function(){
        /* 再弹出添加界面 */
        layer.open({
            type:1,
            title:"添加工单",
            skin:"myclass",
            area:["50%"],
            content:$("#add").html(),
            success:function (layero,index) {
                addAutoComplete(layero);
                layero.addClass('layui-form');
                layero.find('.layui-layer-btn0').attr('lay-filter', 'fromContent').attr('lay-submit', '');//将按钮弄成能提交的
                $(layero).find('select[name=machineType]').html(valMachineType());
                form.on('select(machineTypeFilter)', function(data){
                    changeSubject(layero);
                    form.render();
                });
                form.on('select(addressFilter)', function(data){
                    selectfloor(layero)
                    form.render();
                });
                form.render();
            },
            btn:['提交'],
            yes:function (index,layero) {
                form.on('submit(fromContent)', function (data) {
                    add(index,'1',layero)
                });
            }
        });
    });
// 添加自动填充
function addAutoComplete(layero) {
    autocomplete.render({
        elem: $(layero).find('input[name=email]')[0],
        url: ctx+'/user/findByEmail',
        template_val: '{{d.email}}',
        template_txt: '{{d.email}} <span class=\'layui-badge layui-bg-gray\'>{{d.displayName}}</span>',
        onselect: function (resp) {
            console.info(resp)
        }
    })

}
});


// 给服务时间赋值
function valExpectTime(expectTime) {
    var htmlStr = "<option value=''>请选择...</option>";
    if(expectTime =='上午' || expectTime == '下午'){
        htmlStr+="<option value='上午'>上午</option><option value='下午'>下午</option>";
    }else{
        for(var i=9;i<=17;i+=0.5){
            var time;
            if((i+'').endWith('.5')){
                time  = (i-0.5)+':30  -  '+(i+0.5)+':00';
            }else{
                time = i+':00  -  '+i+':30';
            }
            htmlStr +="<option value='"+time+"'>"+time+"</option>";
        }
    }
    return htmlStr;
}
// 给分类赋值
function valMachineType() {
    var htmlStr = "<option value=''>请选择...</option>";
    $.each(repaireSubject,function (name,value) {
        htmlStr += "<option value = '"+value.value+"'>"+value.text+"</option>";
    });
    return htmlStr;
}
function add(index,status,layero) {
    var email = $(layero).find('input[name=email]').val();
    //var source = $(layero).find('select[name=source]').val();
    var machineType = $(layero).find('select[name=machineType]').val();
    var repaireSubjectVal = $(layero).find('select[name=repaireSubject]').val();
    var address = $(layero).find('select[name=address]').val();
    var floor = $(layero).find('select[name=floor]').val();
    var description = $(layero).find('input[name=description]').val();
    $.ajax({
        url:ctx+'/repaireInfo/add',
        type : 'POST',
        data:
            {email:email,
            machineType:machineType,
            source:'5',// 网页新增类型为 其他 5
            repaireSubject:repaireSubjectVal,
            address:address,
            floor:floor,
            description:description
        },
        success:function (result) {
            var layer = layui.layer;
            var json = JSON.parse(result);
            if(json.code=='0'){
                layer.close(index);
                $('#list').datagrid('reload');
            }else{
                layer.open({
                    title: '报错了'
                    ,content: json.msg
                });
            }

        },
        error:function (result) {
            var json = JSON.parse(result);
            var layer = layui.layer;
            layer.open({
                title: '报错了'
                ,content: json.msg
            });

        }
    });
}
function endServer(id) {
    $.ajax({
        url:ctx+'/repaireInfo/endServer/'+id,
        type : 'POST',
        success:function (result) {
            var json = JSON.parse(result);
            if(json.code=='0'){
                $('#list').datagrid('reload');
            }else{
                layer.open({
                    title: '报错了'
                    ,content: json.msg
                });
            }
        }
    });
}

// 编辑
function editData(id,index) {
    var rows = $('#list').datagrid('getRows');
    var json = rows[index];
    layer.open({
        type: 1,
        title: "编辑",
        skin: "myclass",
        area: ["500px", "500px"],
        content: $("#edit").html(),
        success: function (layero, index) {
            var form = layui.form;
            layero.addClass('layui-form');
            layero.find('.layui-layer-btn0').attr('lay-filter', 'fromContent').attr('lay-submit', '');//将按钮弄成能提交的
            $(layero).find('input[name=id]').val(json.id);
            $(layero).find('input[name=creatorName]').val(json.creatorName);
            $(layero).find('input[name=callerCompanyName]').val(json.callerCompanyName);
            $(layero).find('input[name=description]').val(json.description);
            $(layero).find('input[name=callerDeptName]').val(json.callerDeptName);
            $(layero).find('select[name=expectTime]').html(valExpectTime(json.expectTime));
            $(layero).find('select[name=expectTime]').val(json.expectTime);
            var _address = json.address.split("-")[0];
            $(layero).find('select[name=address] option').each(function (i,n) {
                if($(n).text()==_address) {
                    $(n).attr("selected", true);
                    selectfloor(layero);
                    $(layero).find('select[name=floor]').val(json.floor);
                }
            });
            form.on('select(addressFilter)', function(data){
                selectfloor(layero);
                form.render();
            });
            $(layero).find('select[name=machineType]').html(valMachineType());
            $(layero).find('select[name=machineType] option').each(function(i,n){
                if($(n).text()==json.machineType) {
                    $(n).attr("selected",true);
                    changeSubject(layero);
                    $(layero).find('select[name=repaireSubject]').val(json.repaireSubject);
                }
            });
            form.on('select(machineTypeFilter)', function(data){
                changeSubject(layero);
                form.render();
            });
            form.render();
        },
        btn: ['提交'],
        yes:function (index,layero) {
            var form = layui.form;
            form.on('submit(fromContent)', function (data) {
                var jsonData = $(layero).find("form").toJSON();
                updateByCustomService(jsonData,function () {
                    layer.close(index);
                    $('#list').datagrid('reload');
                });
            });
        }
    })
}

//  选择楼层
function selectfloor(layero) {
    var _address = $(layero).find('select[name=address]').val();
    var $floor = $(layero).find("select[name=floor]");
    $floor.empty();
    var floors= floor_json[_address];
    var floor_html = "";
    $.each(floors,function (i,v) {
        floor_html +="<option value='"+v+"'>"+v+"</option>";
    });
    $floor.html(floor_html);
}
//  更新操作
function handleRecord(id,flag){
        process_01(id,flag);
}
// 售后接单的时候  弹出dialog  选择是否上门服务
// 如果不需要则直接填写相关说明，然后回单到话务员，如果需要，记录当前处理工单的开始时间
function process_01(id, flag) {
    layer.open({
        type:1,
        title:"调配",
        skin:"myclass",
        area:["500px","300px"],
        content:$("#process_01").html(),
        success:function (layero,index) {
            var form = layui.form;
            form.render();
            layero.addClass('layui-form');
            layero.find('.layui-layer-btn0').attr('lay-filter', 'fromContent').attr('lay-submit', '');//将按钮弄成能提交的
            getEngineer(layero,'/repaireInfo/engineer');
        },
        btn:['提交'],
        yes:function (index,layero) {
            var form = layui.form;
            form.on('submit(fromContent)', function (data) {
                var currentId = $(layero).find('select[name=currentId]').val();
                var currentName = $(layero).find('select[name=currentId] option:selected').text();
                var json = {"id":id,"currentId":currentId,"currentName":currentName}
                update(json,function () {
                    layer.close(index);
                    $('#list').datagrid('reload');
                });
            });
        }
    });
}
function renderSelect(data,layero) {
    var optionString = "<option value=''>请选择...</option><option value='group'>IT维护组</option>";
    data.forEach((user,index) =>{
                optionString += "<option value = '"+user.userName+"'>"+user.displayName+"</option>";
            });
    $(layero).find('select[name=currentId]').append(optionString);
    var form = layui.form;
    form.render('select');
}
function getEngineer(layero,pash){
    $.ajax({
        url:ctx + pash,
        method:'get',
        dataType:'json',
        async:false,
        success:function(result){
            if(result.code=='0'){
                renderSelect(result.data,layero);
            }else{
                var layer = layui.layer;
                layer.open({
                    title: '报错了'
                    ,content: result.msg
                });
            }
        },
        error: function (result) {
            var layer = layui.layer;
            layer.open({
                title: '报错了'
                ,content: result.msg
            });
        }
    });
}

function process_2(id, flag) {
    layer.open({
        type:1,
        title:"处理事项",
        skin:"myclass",
        area:["500px","300px"],
        content:$("#huidan").html(),
        success:function (layero,index) {
            var form = layui.form;
            form.render();
            layero.addClass('layui-form');
            layero.find('.layui-layer-btn0').attr('lay-filter', 'fromContent').attr('lay-submit', '');//将按钮弄成能提交的
        },
        btn:['提交'],
        yes:function (index,layero) {
            var form = layui.form;
            form.on('submit(fromContent)', function (data) {
                var reason = $(layero).find('input[name=reason]').val();
                var processSpecification = $(layero).find('input[name=processSpecification]').val();
                var processRemark = $(layero).find('input[name=processRemark]').val();
                var json = {id:id,status:3,processSpecification:processSpecification,processRemark:processRemark,reason:reason};
                update(json,function () {
                    layer.close(index);
                    $('#list').datagrid('reload');
                });
            });
        }
    });
}
function update(json,callback) {
    $.ajax({
        url:ctx+'/repaireInfo/update',
        type : 'POST',
        data:json,
        success:function () {
            if(callback !=null){
                callback();
            }

        }
    });
}

function updateByCustomService(json,callback) {
    $.ajax({
        url:ctx+'/repaireInfo/updateByCustomService',
        type : 'POST',
        data:json,
        success:function () {
            if(callback !=null){
                callback();
            }

        }
    });
}


